package com.itheima.mobile.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.ulits.SMSUtils;
import com.itheima.ulits.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 验证码生成
 *
 * @author ：zengjie
 * @date ：2020/11/14
 */
@RestController
@RequestMapping("/validateCode")
public class MbileValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 体检预约验证码
     *
     * @param telephone
     * @return
     */
    @RequestMapping(value = "/send4Order", method = RequestMethod.POST)
    public Result sendCode(String telephone) {
        return this.getCode(telephone,RedisMessageConstant.SENDTYPE_ORDER);
    }

    private Result getCode(String telephone,String sendType) {
        try {
            //生成一个验证码
            String code = ValidateCodeUtils.generateValidateCode(4) + "";
            //存入redis,定时五分钟
            String key = sendType + "_" + telephone;
            jedisPool.getResource().setex(key, 5 * 60, code);

            //发送短信
            if (false)
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code);
            System.out.println(telephone + " , " + code);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 快速登陆验证码
     */
    @RequestMapping(value = "/send4Login",method = RequestMethod.POST)
    public Result loginCode(String telephone){
        return this.getCode(telephone,RedisMessageConstant.SENDTYPE_LOGIN);
    }
}
